# -*- coding: UTF-8 -*-
__author__ = 'menangen'

import couchdb

couch = couchdb.Server()
db_name = 'test'

#db = couch.create('test')

def createDB():
    try:
        couch.create(db_name)
        print("make new DB")
    except:
        return Exception


def getDocuments():
    docs = []
    try:
        db = couch[db_name]
        if len(db) is not 0:
            for id in db:
                docs.append(id)
    except:
        createDB()
        return Exception
    return docs


def saveDocument(document, DataBase=db_name):
    db = couch[DataBase]
    db.save(document)


def saveComment(nik, comment):
    import commentValidator

    allgood = (commentValidator.validateEmptyString(nik) and commentValidator.validateEmptyString(comment))

    if allgood:
        newcommentdoc = {'name': str(nik), 'text': str(comment)}
        print newcommentdoc
        saveDocument(newcommentdoc)
        return True

    else:
        return False


def getAll():
    db = {}
    try:
        db = couch[db_name]
    except:
        try:
            createDB()
        except:
            return "Please run CouchServer"

    try:
        data = []
        if len(db) is not 0:
            for id in db:
                data.append({'id': id, 'name':db[id]['name'], 'commet':db[id]['text']})
        return data
    except:
        pass




        #testDoc = {'name':'andrey', 'text':'hello'}
        #saveDocument(testDoc, 'test')

def test():
    db = couch[db_name]
    data = []
    for id in db:
        data.append({'id': id, 'name':db[id]['name'], 'commet':db[id]['text']})
    print data
